<template>
  <view class="container">
    <view class="header">
      <view class="back-btn" @tap="goBack">
        <text class="iconfont icon-back"></text>
      </view>
    </view>
    <view class="logo">
      <image src="http://114.55.56.174:19000/shzy/仙云.png" mode="aspectFit"></image>
      <text>山海之约</text>
    </view>

    <view v-if="loginType === 'wechat'">
      <!-- 微信授权登录 -->
      <view class="wechat-login">
        <view class="wechat-header">
          <image src="/static/images/wechat.png" class="wechat-icon"></image>
          <text>使用微信快捷登录</text>
        </view>
        
        <!-- <view class="iconfont-container">
          <text>[iconfont]</text>
        </view> -->
        
        <view class="user-info">
          <image :src="userInfo.avatar || 'http://114.55.56.174:19000/shzy/avatar.png'" class="avatar"></image>
          <text>{{userInfo.nickname || '高城司'}}</text>
        </view>
        
        <view v-if="loginStep === 1">
          <button class="wechat-btn" @tap="handleWechatLogin">微信快捷登录</button>
        </view>
        
        <view v-else-if="loginStep === 2">
          <text class="login-status">登录中...</text>
        </view>
        
        <view v-else-if="loginStep === 3">
          <view class="auth-prompt">
            <text class="auth-title">山海之约申请使用</text>
            <text class="auth-desc">你的头像、昵称</text>
            
            <view class="auth-user-info">
              <image :src="userInfo.avatar || 'http://114.55.56.174:19000/shzy/avatar.png'" class="avatar"></image>
              <text>{{userInfo.nickname || '高城司'}}</text>
            </view>
            
            <view class="auth-btns">
              <button class="auth-btn allow" @tap="handleAllowAuth">允许</button>
              <button class="auth-btn reject" @tap="handleRejectAuth">拒绝</button>
            </view>
          </view>
        </view>
        
        <view class="switch-login">
          <text @tap="switchLoginType('phone')">手机号登录</text>
        </view>
      </view>
    </view>

    <view v-else>
      <!-- 手机号登录表单 -->
      <view class="login-form">
        <view class="input-group">
          <text class="iconfont icon-phone"></text>
          <input type="number" v-model="phone" placeholder="请输入手机号" maxlength="11" />
        </view>
        <view class="input-group">
          <text class="iconfont icon-verify"></text>
          <input type="number" v-model="code" placeholder="请输入验证码" maxlength="6" />
          <text class="verify-btn" :class="{ disabled: counting }" @tap="getVerifyCode">
            {{counting ? `${countdown}s后重新获取` : '获取验证码'}}
          </text>
        </view>
        <button class="login-btn" @tap="login">登录</button>
        <button class="guest-btn" @tap="guestLogin">游客浏览</button>
        <view class="agreement">
          登录即代表您已同意
          <text class="link" @tap="goToAgreement('user')">《用户协议》</text>
          和
          <text class="link" @tap="goToAgreement('privacy')">《隐私政策》</text>
        </view>
      </view>

      <!-- 第三方登录 -->
      <view class="third-party">
        <view class="divider">
          <text>其他登录方式</text>
        </view>
        <view class="login-methods">
          <view class="method" @tap="switchLoginType('wechat')">
            <image src="http://114.55.56.174:19000/shzy/微信.png" class="login-icon"></image>
            <text>微信</text>
          </view>
          <!-- <view class="method" @tap="thirdPartyLogin('qq')">
            <image src="/static/images/QQ.png" class="login-icon"></image>
            <text>QQ</text>
          </view> -->
          <view class="method" @tap="faceRecognitionLogin">
            <image src="http://114.55.56.174:19000/shzy/人脸识别.png" class="login-icon"></image>
            <text>人脸识别</text>
          </view>
          <view class="method" @tap="faceRegistration">
            <image src="http://114.55.56.174:19000/shzy/人脸录入.png" class="login-icon"></image>
            <text>人脸录入</text>
          </view>
        </view>

      </view>
    </view>
  </view>
</template>

<script>
import request from '@/utils/request'
import { SERVICE_PREFIX } from '@/utils/request'

export default {
  data() {
    return {
      phone: '',
      code: '',
      counting: false,
      countdown: 60,
      isGuest: false,
      loginType: 'phone', // 'phone' 或 'wechat'
      loginStep: 1, // 微信登录步骤: 1-初始, 2-登录中, 3-授权
      userInfo: {
        avatar: '',
        nickname: ''
      },
      wxLoginInfo: {
        code: '',
        avatarUrl: '',
        nickName: ''
      }
    }
  },
  onLoad() {
    // 检查是否是游客模式，但不自动触发游客登录
    this.isGuest = uni.getStorageSync('isGuest') || false
  },
  methods: {
    getVerifyCode() {
      if (this.counting) return
      
      // 验证手机号
      if (!/^1[3-9]\d{9}$/.test(this.phone)) {
        uni.showToast({
          title: '请输入正确的手机号',
          icon: 'none'
        })
        return
      }
      
      // 开始倒计时
      this.counting = true
      this.countdown = 60
      
      const timer = setInterval(() => {
        this.countdown--
        if (this.countdown <= 0) {
          clearInterval(timer)
          this.counting = false
        }
      }, 1000)
      
      // 调用后端发送验证码接口
      uni.showLoading({
        title: '发送中...'
      })
      
      // 使用封装的请求方法调用后端接口
      request.login.get('/api/user/sendCode', { phone: this.phone })
        .then(res => {
          uni.hideLoading()
          uni.showToast({
            title: '验证码已发送',
            icon: 'success'
          })
        })
        .catch(err => {
          uni.hideLoading()
          // 发送失败不停止倒计时，允许用户重试
          console.error('验证码发送失败:', err)
        })
    },
    
    guestLogin() {
      // 设置游客模式
      uni.setStorageSync('isGuest', true)
      uni.switchTab({
        url: '/pages/index/index'
      })
    },
    
    login() {
      if (!this.phone || !this.code) {
        uni.showToast({
          title: '请输入手机号和验证码',
          icon: 'none'
        })
        return
      }
      
      // 验证手机号格式
      if (!/^1[3-9]\d{9}$/.test(this.phone)) {
        uni.showToast({
          title: '请输入正确的手机号',
          icon: 'none'
        })
        return
      }
      
      // 显示加载中
      uni.showLoading({
        title: '登录中...'
      })
      
      // 准备登录参数
      const loginParams = {
        phone: this.phone,
        code: this.code
      }
      
      // 调用后端登录接口
      request.login.post('/api/user/login', loginParams)
        .then(res => {
          uni.hideLoading()
          
          // 清除游客模式
          uni.removeStorageSync('isGuest')
          
          // 保存返回的token
          if (res.data) {
            uni.setStorageSync('userInfo', res.data)
            uni.setStorageSync('token', res.data)
            
            // 登录成功
            uni.showToast({
              title: res.errorMessage || '登录成功',
              icon: 'success'
            })
            
            // 跳转到首页
            setTimeout(() => {
              uni.reLaunch({
                url: '/pages/index/index'
              })
            }, 1500)
          } else {
            uni.showToast({
              title: '登录失败，请重试',
              icon: 'none'
            })
          }
        })
        .catch(err => {
          uni.hideLoading()
          uni.showToast({
            title: err.message || '登录失败，请重试',
            icon: 'none'
          })
        })
    },
    
    switchLoginType(type) {
      this.loginType = type
      this.loginStep = 1
    },
    
    handleWechatLogin() {
      // 使用新版本的getUserProfile API获取用户信息
      uni.getUserProfile({
        desc: '用于完善会员资料', // 声明获取用户个人信息后的用途
        success: (res) => {
          console.log('获取用户信息成功：', res)
          // 保存用户信息
          this.userInfo = {
            avatar: res.userInfo.avatarUrl,
            nickname: res.userInfo.nickName
          }
          
          // 保存用户信息用于后续登录
          this.wxLoginInfo = {
            avatarUrl: res.userInfo.avatarUrl,
            nickName: res.userInfo.nickName
          }
          
          // 获取用户信息成功后，再获取登录凭证
          this.loginStep = 2 // 登录中...
          
          uni.login({
            provider: 'weixin',
            success: (loginRes) => {
              console.log('获取登录凭证成功：', loginRes)
              // 获取到临时登录凭证code
              this.wxLoginInfo.code = loginRes.code
              
              // 显示授权页面
              this.loginStep = 3
            },
            fail: (err) => {
              console.error('微信登录失败:', err)
              uni.showToast({
                title: '微信登录失败',
                icon: 'none'
              })
              this.loginStep = 1
            }
          })
        },
        fail: (err) => {
          console.error('获取用户信息失败:', err)
          uni.showToast({
            title: '获取用户信息失败',
            icon: 'none'
          })
          this.loginStep = 1
        }
      })
    },
    
    onGetUserInfo(e) {
      console.log('获取用户信息响应：', e)
      if (e.detail.userInfo) {
        // 用户同意授权
        this.userInfo = {
          avatar: e.detail.userInfo.avatarUrl,
          nickname: e.detail.userInfo.nickName
        }
        
        // 保存用户信息用于后续登录
        this.wxLoginInfo = {
          ...this.wxLoginInfo, // 保留之前的code
          avatarUrl: e.detail.userInfo.avatarUrl,
          nickName: e.detail.userInfo.nickName
        }
      } else {
        // 用户拒绝授权
        console.error('用户拒绝授权:', e.detail)
        uni.showToast({
          title: '获取用户信息失败',
          icon: 'none'
        })
        this.loginStep = 1
      }
    },
    
    handleAllowAuth() {
      // 用户同意授权，进行微信登录
      uni.showLoading({
        title: '授权登录中...'
      })
      
      // 确保wxLoginInfo中有必要的信息
      if (!this.wxLoginInfo.code) {
        uni.hideLoading()
        uni.showToast({
          title: '登录失败，请重试',
          icon: 'none'
        })
        this.loginStep = 1
        return
      }
      
      // 准备登录参数，与后端接口对应
      const loginParams = {
        appid: 'wx8df8a9ee41207afe',
        secret: 'ed6d99aab704abd9155f543072771ebf',
        avatarUrl: this.wxLoginInfo.avatarUrl,
        nickName: this.wxLoginInfo.nickName,
        code: this.wxLoginInfo.code
      }
      
      console.log('微信登录参数：', loginParams)
      
      // 调用后端微信登录接口
      request.login.post('/api/user/wxlogin', loginParams)
        .then(res => {
          uni.hideLoading()
          console.log('微信登录响应：', res)
          
          // 清除游客模式
          uni.removeStorageSync('isGuest')
          
          // 保存返回的用户信息和token
          if (res.data) {
            uni.setStorageSync('token', res.data.token || res.data)
            uni.setStorageSync('userInfo', res.data)
            
            uni.showToast({
              title: res.message || '登录成功',
              icon: 'success'
            })
            
            setTimeout(() => {
              uni.switchTab({
                url: '/pages/index/index'
              })
            }, 1500)
          } else {
            uni.showToast({
              title: '登录失败，请重试',
              icon: 'none'
            })
          }
        })
        .catch(err => {
          console.error('微信登录错误：', err)
          uni.hideLoading()
          uni.showToast({
            title: err.message || '登录失败，请重试',
            icon: 'none'
          })
        })
    },
    
    handleRejectAuth() {
      // 用户拒绝授权
      this.loginStep = 1 // 返回初始状态
      uni.showToast({
        title: '您已拒绝授权',
        icon: 'none'
      })
    },
    
    thirdPartyLogin(type) {
      uni.showToast({
        title: '暂未开放，请使用微信或手机号登录',
        icon: 'none'
      })
    },
    
    faceRecognitionLogin() {
      // 跳转到人脸识别登录页面
      uni.navigateTo({
        url: '/pages/login/face-recognition'
      })
    },
    
    faceRegistration() {
      // 跳转到人脸录入页面
      uni.navigateTo({
        url: '/pages/login/face-recognition?mode=register'
      })
    },
    
    goToAgreement(type) {
      uni.navigateTo({
        url: `/pages/agreement/${type}`
      })
    },
    
    goBack() {
      // 修改返回按钮行为，点击返回主页
      uni.switchTab({
        url: '/pages/index/index'
      })
    }
  }
}
</script>

<style lang="scss">
.container {
  min-height: 100vh;
  background: #fff;
  padding: 60rpx 40rpx;
}

.header {
  display: flex;
  align-items: center;
  margin-bottom: 80rpx;
  
  .back-btn {
    padding: 20rpx;
  }
}

.logo {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 80rpx;
  
  image {
    width: 160rpx;
    height: 160rpx;
    margin-bottom: 20rpx;
  }
  
  text {
    font-size: 36rpx;
    font-weight: bold;
    color: #333;
  }
}

.login-form {
  .input-group {
    display: flex;
    align-items: center;
    height: 100rpx;
    border-bottom: 1rpx solid #eee;
    margin-bottom: 40rpx;
    
    .iconfont {
      font-size: 40rpx;
      color: #999;
      margin-right: 20rpx;
    }
    
    input {
      flex: 1;
      height: 100%;
      font-size: 32rpx;
    }
    
    .verify-btn {
      font-size: 28rpx;
      color: #4080ff;
      padding: 0 20rpx;
      
      &.disabled {
        color: #999;
      }
    }
  }
  
  .login-btn {
    width: 100%;
    height: 88rpx;
    line-height: 88rpx;
    background: #4080ff;
    color: #fff;
    font-size: 32rpx;
    border-radius: 44rpx;
    margin: 60rpx 0 40rpx;
  }
  
  .guest-btn {
    width: 100%;
    height: 88rpx;
    line-height: 88rpx;
    background: #f5f5f5;
    color: #666;
    font-size: 32rpx;
    border-radius: 44rpx;
    margin: 20rpx 0 40rpx;
  }
  
  .agreement {
    text-align: center;
    font-size: 24rpx;
    color: #999;
    
    .link {
      color: #4080ff;
    }
  }
}

.third-party {
  margin-top: 100rpx;
  
  .divider {
    position: relative;
    text-align: center;
    margin-bottom: 60rpx;
    
    &::before,
    &::after {
      content: '';
      position: absolute;
      top: 50%;
      width: 30%;
      height: 1rpx;
      background: #eee;
    }
    
    &::before {
      left: 0;
    }
    
    &::after {
      right: 0;
    }
    
    text {
      display: inline-block;
      padding: 0 20rpx;
      font-size: 28rpx;
      color: #999;
      background: #fff;
      position: relative;
      z-index: 1;
    }
  }
  
  .login-methods {
    display: flex;
    justify-content: center;
    
    .method {
      display: flex;
      flex-direction: column;
      align-items: center;
      margin: 0 40rpx;
      
      .login-icon {
        width: 100rpx;
        height: 100rpx;
        border-radius: 50%;
        margin-bottom: 20rpx;
        object-fit: contain;
        background-color: #f5f5f5;
        padding: 10rpx;
      }
      
      text {
        font-size: 28rpx;
        color: #666;
      }
    }
  }
}

// 微信授权登录样式
.wechat-login {
  display: flex;
  flex-direction: column;
  align-items: center;
  
  .wechat-header {
    display: flex;
    flex-direction: column;
    align-items: center;
    margin-bottom: 30rpx;
    
    .wechat-icon {
      width: 120rpx;
      height: 120rpx;
      margin-bottom: 20rpx;
    }
    
    text {
      font-size: 32rpx;
      color: #333;
    }
  }
  
  .iconfont-container {
    margin-bottom: 30rpx;
    
    text {
      font-size: 32rpx;
      color: #666;
      font-weight: bold;
    }
  }
  
  .user-info {
    display: flex;
    flex-direction: column;
    align-items: center;
    margin-bottom: 60rpx;
    
    .avatar {
      width: 120rpx;
      height: 120rpx;
      border-radius: 50%;
      margin-bottom: 20rpx;
    }
    
    text {
      font-size: 32rpx;
      color: #333;
    }
  }
  
  .wechat-btn {
    width: 600rpx;
    height: 88rpx;
    line-height: 88rpx;
    background: #07c160;
    color: #fff;
    font-size: 32rpx;
    border-radius: 44rpx;
  }
  
  .login-status {
    font-size: 32rpx;
    color: #666;
  }
  
  .auth-prompt {
    width: 600rpx;
    background: #fff;
    border-radius: 20rpx;
    box-shadow: 0 0 20rpx rgba(0, 0, 0, 0.1);
    padding: 40rpx;
    margin-bottom: 60rpx;
    
    .auth-title {
      display: block;
      font-size: 36rpx;
      font-weight: bold;
      color: #333;
      margin-bottom: 20rpx;
      text-align: center;
    }
    
    .auth-desc {
      display: block;
      font-size: 32rpx;
      color: #666;
      margin-bottom: 40rpx;
      text-align: center;
    }
    
    .auth-user-info {
      display: flex;
      align-items: center;
      margin-bottom: 40rpx;
      
      .avatar {
        width: 80rpx;
        height: 80rpx;
        border-radius: 50%;
        margin-right: 20rpx;
      }
      
      text {
        font-size: 32rpx;
        color: #333;
      }
    }
    
    .auth-btns {
      display: flex;
      justify-content: space-between;
      
      .auth-btn {
        width: 240rpx;
        height: 80rpx;
        line-height: 80rpx;
        font-size: 32rpx;
        border-radius: 40rpx;
        
        &.allow {
          background: #07c160;
          color: #fff;
        }
        
        &.reject {
          background: #f5f5f5;
          color: #666;
        }
      }
    }
  }
  
  .switch-login {
    margin-top: 60rpx;
    
    text {
      font-size: 28rpx;
      color: #4080ff;
    }
  }
}
</style> 